package handler

import (
	"common"
	"common/biz"
	"common/logs"
	"connector/models/request"
	"context"
	"core/repo"
	"core/service"
	"encoding/json"
	"fmt"
	"framework/net"
	"unicode/utf8"
)

type EntryHandler struct {
	userService *service.UserService
}

func (h *EntryHandler) Entry(session *net.Session, body []byte) (any, error) {
	logs.Info("======================== Entry Start ==================================")
	logs.Info("entry request params:%v", string(body))
	logs.Info("======================== Entry End ==================================")
	var req request.EntryReq
	err := json.Unmarshal(body, &req)
	if err != nil {
		return common.F(biz.RequestDataError), nil
	}

	//校验token
	ctx := context.TODO()
	uid := h.userService.GetUID(ctx, req.Token)
	if uid == 0 {
		return common.F(biz.InvalidUsers), nil
	}
	if req.UserInfo.Avatar != "" {
		if utf8.RuneCountInString(req.UserInfo.Nickname) < 1 || utf8.RuneCountInString(req.UserInfo.Nickname) > 6 {
			return common.F(biz.NicknameLenError), nil
		}
	}
	// 根据uid 去mysql 查询用户 如果角色不存在 生成一个角色
	user, err := h.userService.FindAndSaveUserByUid(context.TODO(), uid, session.Sid, &req.UserInfo)
	if err != nil {
		return common.F(biz.InvalidUsers), nil
	}
	if user.Status == 9 {
		return common.F(biz.UserClenLoginError), nil
	}
	if user.Status == -1 {
		return common.F(biz.BlockedAccount), nil
	}
	if user.RealMsg.IDCard != "" {
		user.RealMsg.IDCard = fmt.Sprintf("%v***********%v", user.RealMsg.IDCard[0:3], user.RealMsg.IDCard[14:])
	}
	session.Uid = fmt.Sprintf("%d", uid)
	return common.S(map[string]any{
		"userInfo": user,
		"config": map[string]any{
			"types": h.userService.TypeAll(ctx),
			"conf":  h.userService.GetConfAll(ctx),
			"bank":  h.userService.GetBank(ctx),
		},
	}), nil
}

func NewEntryHandler(r *repo.Manager) *EntryHandler {
	return &EntryHandler{
		userService: service.NewUserService(r),
	}
}
